package kyssion.leetcode.num151_200;

import kyssion.leetcode.util.ListNode;

public class code160_链表相交 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int aLength = 0;
        int bLength = 0;
        ListNode h1 = headA;
        ListNode h2 = headB;
        while (h1 != null) {
            aLength++;
            h1 = h1.next;
        }
        while (h2 != null) {
            bLength++;
            h2 = h2.next;
        }
        int speed;
        if (aLength < bLength) {
            h1 = headA;
            headA = headB;
            headB = h1;
            speed = aLength;
            aLength = bLength;
            bLength = speed;
        }
        speed = aLength - bLength;
        while (speed > 0) {
            headA = headA.next;
            speed--;
        }

        while (true) {
            if(headA==headB){
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
        }
    }
}
